const Koa = require('koa')
const app = new Koa()
const urlParse = require('url')
const fs = require('fs')
const moment = require('moment')
const bodyParser = require('koa-bodyparser')
const convert = require('koa-convert')
const isProduction = process.env.NODE_ENV === 'production';
const mySocket = require('./socket/test')
const static = require('koa-static')
var server = require('http').Server(app.callback());
var io = require('socket.io')(server);
require('./db')
app.use(bodyParser());
const cors = require('koa2-cors');
app.use(static(__dirname + '/public'))
app.use(cors({
  origin: function (ctx) {
    if (ctx.url === '/test') {
      return "*"; // 允许来自所有域名请求
    }
    return "*";
  },
  exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'],
  maxAge: 5,
  credentials: true,
  allowMethods: ['GET', 'POST', 'DELETE', 'PUT'],
  allowHeaders: ['Content-Type', 'Authorization', 'Accept'],
}))
app.use(async (ctx, next) => {
  var ws = fs.createWriteStream('log.txt', {
    flags: 'a'
  })
  var dateTime = moment().format('YYYY-MM-DD HH:mm:ss')
  var data = {
    time: dateTime,
    method: ctx.method,
    api: ctx.url
  }
  ws.write(JSON.stringify(data) + ',\n')
  await next()
})
app.use(require('./controllers/index').routes())


server.listen(8020)

io.on('connection', function (socket) {
  console.log('socket连接成功')
  mySocket(socket)
})

console.log('app started at port 8020...');